﻿using System;
using System.Disposables;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using SoftSource.Common;
using SoftSource.MVVMC;
using SoftSource.Reactive;
using SoftSource.Timecard.ViewModelInterfaces;
using SoftSource.Timecard.Web.Data;

namespace SoftSource.Timecard
{
    public sealed partial class UserListView : UserControl, IView<IUserListViewModelConsume>, IDisposable
    {
        #region Fields
        private CompositeDisposable compositeDisposable;
        private Filter<UserSummary> filter;
        private string nameFilter;
        private Predicate<UserSummary> checkBoxFilter;
        #endregion Fields

        public UserListView()
        {
            InitializeComponent();

            this.compositeDisposable = new CompositeDisposable();

            Loaded += new RoutedEventHandler(UserListView_Loaded);
        }

        #region Events

        private void UserListView_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.ViewModel != null)
            {
                this.ViewModel.Load // Load the data required to use this ViewModel
                    .Nullable()
                    .Subscribe(unit =>
                        {
                            this.Busy.IsBusy = false;
                            this.filter = this.ViewModel.Users.AttachFilter<UserSummary>();
                            this.AttatchFilters();
                            this.RunFilters();
                        });
            }

            var beginningEditDisposable = this.UserDataGrid
                .WhenBeginningEdit()
                .Subscribe(args =>
                    {
                        args.EventArgs.Cancel = true;
                        var summary = args.EventArgs.Row.DataContext as UserSummary;

                        if (summary != null)
                        {
                            Func<Action, UIElement> editorCreator = completed => this.ViewModel.CreateUserEditor.TryInvoke(summary.UserID, completed);
                            this.OpenEditor(editorCreator);
                        }
                    });

            var throttledFilterDisposable = Observable.FromEvent<TextChangedEventHandler, TextChangedEventArgs>(
                handler => (sender2, e2) => handler(sender2, e2),
                handler => this.FilterTextBox.TextChanged += handler,
                handler => this.FilterTextBox.TextChanged -= handler)
                .Throttle(TimeSpan.FromSeconds(0.2))
                .DistinctUntilChanged()
                .Subscribe(args =>
                {
                    this.nameFilter = this.FilterTextBox.Text.ToLower();
                    this.RunFilters();
                });

            this.compositeDisposable.Add(beginningEditDisposable);
            this.compositeDisposable.Add(throttledFilterDisposable);

            this.RunFilters();
        }

        private void AttatchFilters()
        {
            this.filter.Add(summary =>
                {
                    if (string.IsNullOrEmpty(this.nameFilter))
                        return true;

                    if (summary != null && !string.IsNullOrEmpty(summary.FullName))
                    {
                        return summary.FullName.ToLower().Contains(this.nameFilter);
                    }
                    else
                    {
                        return false;
                    }
                });
            this.filter.Add(summary => this.checkBoxFilter(summary));
        }

        private void CheckBoxFilter_CheckChanged(object sender, RoutedEventArgs e)
        {
            this.EvaluateCheckBoxes();
            this.RunFilters();
        }

        private void AddNew_Click(object sender, RoutedEventArgs e)
        {
            var summary = this.UserDataGrid.SelectedItem as UserSummary;

            if (summary != null)
            {
                this.OpenEditor(completed => this.ViewModel.CreateNewUserEditor(() => 
                    {
                        completed();
                        this.ViewModel.Users.MoveCurrentToLast();
                    }));
            }
        }

        #endregion Events

        #region Methods
        private void OpenEditor(Func<Action, UIElement> createEditor)
        {
            ChildWindow cw = new ChildWindow();
            cw.Title = "Edit User";
            cw.HasCloseButton = false;

            UIElement editor = createEditor.TryInvoke(cw.Close);

            cw.Content = editor;
            cw.Show();
        }

        private void RunFilters()
        {
            if (this.filter != null)
                this.filter.Refresh.TryInvoke();
        }

        private void EvaluateCheckBoxes()
        {
            this.checkBoxFilter = summary =>
            {
                if (summary.IsActive)
                    return true; // Always include active

                if (!this.ActiveCheckBox.IsChecked ?? false)
                    return true; // If the User is not active, but the checkbox is unchecked, then include it

                return false; // if the User doesn't match either of the above criteria, then don't include it
            };
        }
        #endregion Methods

        #region IView<IUserListViewModel> Members

        public IUserListViewModelConsume ViewModel
        {
            get { return this.DataContext as IUserListViewModelConsume; }
            set { this.DataContext = value; }
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            this.compositeDisposable.Dispose();
        }

        #endregion
    }
}